<?php
namespace Admin\Controller;

class AuthRuleController extends AdminController {
	function index() {
		if (isset($_GET['pid'])) {
			$listMap['pid'] = I('pid');
			$info = D('AuthRule')->info(I('pid'));
			$listTitle = ' ['.$info['title'].']';
		}else {
			$listMap['pid'] = 0;
		}
		if (!isset($listTitle)) $listTitle = ' [根节点]';
		$lists = $this->lists(D('AuthRule'),$listMap,'sort asc');
		//字段映射
		$map['pid'] = D('AuthRule')->getField('id,title,pid');
		foreach ($lists as $k=>$v) {
			$lists[$k]['child'] = D('AuthRule')->where('pid='.$v['id'])->count();
		}
		$lists = int_to_string($lists,$map);
		//赋值
		$this->assign('_list',$lists);
		$this->_meta_title('权限节点'.$listTitle);
		$this->display('Auth/Rule/index');
	}
	function add() {
		if (IS_POST) {
			$model = D('AuthRule');
			if (!$model->create()) {
				$this->error($model->getError());
			}else {
				if ($model->add()) {
					$this->success('添加节点成功！',I('get.url',U('index')));
				}else {
					$this->error('添加节点失败！');
				}
			}
		}else {
			$nodes = D('AuthRule')->lists();
			$nodes = D('Common/Tree')->toFormatTree($nodes);
			$this->assign('parents_nodes',$nodes);
			$this->_meta_title('新增节点');
			$this->display('Auth/Rule/edit');
		}
	}
	function edit($id) {
		if (IS_POST) {
			$model = D('AuthRule');
			if (!$model->create()) {
				$this->error($model->getError());
			}else {
				if ($model->save()) {
					$this->success('编辑节点成功！',I('get.url',U('index')));
				}else {
					$this->error('编辑节点失败！');
				}
			}
		}else {
			$nodes = D('AuthRule')->lists();
			$nodes = D('Common/Tree')->toFormatTree($nodes);
			$this->assign('parents_nodes',$nodes);
			$info = D('AuthRule')->info($id);
			$this->assign('info',$info);
			$this->_meta_title('编辑节点');
			$this->display('Auth/Rule/edit');
		}
	}
	function del() {
		if ($this->delete(D('AuthRule'), I('id'))) {
			$this->success('删除节点成功！');
		}else {
			$this->error('删除节点失败！');
		}
	}
	function forb($id, $status) {
		if ($status==1) {
			if ($this->forbidden(D('AuthRule'), $id)) {
				$this->success('禁用节点成功！');
			}else {
				$this->error('禁用节点失败！');
			}
		}else {
			if ($this->restore(D('AuthRule'), $id)) {
				$this->success('启用节点成功！');
			}else {
				$this->error('启用节点失败！');
			}
		}
	}
}